/**
 * 储存器封装
 * 
 * @author Gill Gong
 */

//import { AsyncStorage } from '@react-native-community/async-storage'
import { AsyncStorage } from 'react-native'

const __Golobal_Key = "__golbal_cache_key"
let __Golobal_Cache = {}

export default {

  set(key, value) {

    return new Promise(function(resolve, reject) {
      __Golobal_Cache[ key ] = value

      AsyncStorage.setItem(__Golobal_Key, JSON.stringify(__Golobal_Cache), function(error) {
   
        if(error) {
          reject(false)
        }else{
          resolve(true)
        }
      })
    })
  },

  get(key) {

    return new Promise(function(resolve, reject) {

      AsyncStorage.getItem(__Golobal_Key, function(error, result) {
      
        if(error) {
          
          reject(null)
        }else{

          if(_.isString(result) && result.length) {
            result = JSON.parse(result)
            resolve(result[key])
          }else{
            resolve(null)
          }
        }
      })
    })
  },

  remove(key) {

    return new Promise(function(resolve, reject) {
      delete __Golobal_Cache[ key ]

      AsyncStorage.setItem(__Golobal_Key, JSON.stringify(__Golobal_Cache), function(error) {
        if(error) {
          reject(false)
        }else{
          resolve(true)
        }
      })
    })
  },

  getTokenSync() {

    return __Golobal_Cache[ '___token' ] || null
  },

  getToken() {

    return this.get('___token')
  },

  setToken(token) {

    return this.set('___token', token)
  },

  clearToken() {

    return this.remove('___token')
  },

  setUser(user) {

    __Golobal_Cache[ '___user' ] = user
  },

  getUser() {

    return __Golobal_Cache[ '___user' ]
  }
}